var express = require('express');
var crypto = require('crypto');
var multipart = require('connect-multiparty');
var os = require('os');
var fs = require('fs');
var path = require('path');
var multipartMiddleware = multipart({
	uploadDir : BASE_CONFIG.tmpDir || os.tmpdir()
});
var router = express.Router();

router.post('/', multipartMiddleware, function (req, res, next) {
	var file = req.files.file;
	console.log(file);
	if (!file) {
		res.send(400);
		return;
	}
	
	var dbFile = new Db.File(file);
	
	var id = dbFile._id.toString();
	var filePath = path.join(BASE_CONFIG.fileDir, id);
	
	// 复制文件同时计算MD5摘要
	var md5 = '';
	var md5sum = crypto.createHash('md5');
	var writeStream = fs.WriteStream(filePath);
	var readStream = fs.ReadStream(file.path);
	readStream.on('data', function(d) {
		md5sum.update(d);
		writeStream.write(d);
	}).on('end', function() {
		dbFile.md5 = md5sum.digest('hex');
		dbFile.path = filePath;
		writeStream.end();
		
		dbFile.save(function(err) {
			if (err) {
				res.send(500, err);
				return;
			}
			
			res.type('application/json');
			res.send(dbFile);
		});
	}).on('error', function(err) {
		res.send(500, err);
	});
});

router.get('/:id', function(req, res) {
	var id = req.params.id;
	if (!id) {
		res.send(404);
		return;
	}
	
	Db.File.findById(id, function(err, file) {
		if (err) {
			res.send(500, err);
			return;
		}
		
		if (file) {
			res.type(file.type);
			res.attachment(file.originalFilename);
			res.sendFile(file.path, function(err) {
				if (err) {
					console.error(err);
				}
			});
		} else {
			res.send(404);
		}
	});
});

module.exports = router;
